/* 结合讲义中关于箭头运算符重载的案例，
 * 实现第三层对象可以访问并自动回收第一层对象的效果。 */
#include <iostream>
using std::cout;
using std::endl;

//内层
class InLayer{
private:
    int m_data;
public:
    InLayer(int data = 0)
        :m_data(data)
    {}
    int get_data() {
        return m_data;
    }
};//end of class InLayer
//中层
class MiddleLayer{
private:
    InLayer * m_inlayer;
public:
    MiddleLayer(InLayer * p)
        :m_inlayer(p)
    {}
    ~MiddleLayer() {
        if (m_inlayer) {
            delete m_inlayer;
            m_inlayer = nullptr;
        }
    }
    //->重载
    InLayer * operator->() {
        return m_inlayer;
    }
    //*重载
    InLayer & operator*() {
        return *m_inlayer;
    }
};//end of class MidleLayer
//外层
class ThirdLayer{
    MiddleLayer * m_middlelayer;
public:
    ThirdLayer(MiddleLayer* p)
        :m_middlelayer(p)
    {}
    ~ThirdLayer() {
        if (m_middlelayer) {
            delete m_middlelayer;
            m_middlelayer =nullptr;
        }
    }
    //->重载
    MiddleLayer & operator->() {
        return *m_middlelayer;
    }
    //*重载
    InLayer & operator*() {
        return **m_middlelayer;
    }
};//end of class ThirdLayer
int main()
{
    ThirdLayer thirdlayer(new MiddleLayer(new InLayer(10)));
    cout << thirdlayer->get_data() << endl;
    cout << (*thirdlayer).get_data() << endl;
    return 0;
}

